<?php
// include(dirname(__FILE__) . "/util.php");
include_once(dirname(__FILE__) . "/comment-service-adapter.php");
include_once(dirname(__FILE__) . "/related-recomm-adapter.php");

include_once(dirname(__FILE__) . "/env-config.php");
$conn = mysql_connect("127.0.0.1","root","");
mysql_select_db("xingtan");
$article_id = intval($_GET['id']);

$article_meta = GetArticleMeta($article_id);

$sql=sprintf("SELECT a.id AS a_id, a.title AS a_title, a.url AS a_url, a.create_time AS a_create_time,
    u.id AS u_id, u.name AS u_name, u.title AS u_title, u.url AS u_url
    FROM articles AS a, authors AS u WHERE a.category >= 0 AND a.author = u.id AND a.id > %d LIMIT 1", $article_id);
$result = mysql_query($sql);
if($result) {
  $newer_row = mysql_fetch_array($result);
}

$sql=sprintf("SELECT a.id AS a_id, a.title AS a_title, a.url AS a_url, a.create_time AS a_create_time,
    u.id AS u_id, u.name AS u_name, u.title AS u_title, u.url AS u_url
    FROM articles AS a, authors AS u WHERE a.category >= 0 AND a.author = u.id AND a.id < %d ORDER BY a.id DESC LIMIT 1", $article_id);

if (!($category_map = apc_fetch('category-map'))) {
  $category_map = array();
  $sql=sprintf("SELECT id, name, title FROM categories;");
  $result = mysql_query($sql);
  while($r = mysql_fetch_array($result)) {
    $category_map[$r['id']] = $r;
  }
  apc_add('category-map', $category_map, 3600);
}

$result = mysql_query($sql);
if($result) {
  $elder_row = mysql_fetch_array($result);
}
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<?php
printf('<title>%s - 价值投资派</title>', stripslashes($article_meta['a_title']));
?>
<link href="/css/core.css?v=11" rel="stylesheet" type="text/css"></link>
<script type="text/javascript">
<?php
printf("var article_id = %d;", $article_id);
?>
</script>
</head>
<body>
<?php
function NewerElderNav($row_newer, $row_elder) {
  print('<div class="neighbors-nav"><div class="neighbor-prev">');
  if($row_newer) {
    printf('<a href="/a/%d.html"><span style="font-size:9px;">&lt;&lt;</span>较新一篇：%s</a>', $row_newer['a_id'], stripslashes($row_newer['a_title']));
  } else {
    printf('<a href="/?f=prev"><span style="font-size:9px;">&lt;&lt; </span>更多...</a>');
  }
  print('</div><div class="neighbor-next">');
  if($row_elder) {
    printf('<a style="text-align:right;" href="/a/%d.html">较旧一篇：%s<span style="font-size:9px;">&gt;&gt;</span></a>', $row_elder['a_id'], stripslashes($row_elder['a_title']));
  } else {
    printf('<a href="/?f=next">更多...<span style="font-size:9px;"> &gt;&gt;</span></a>');
  }
  print('</div></div>');
}
?>

<?php
include_once(dirname(__FILE__) . "/account/account.php");
include_once(dirname(__FILE__) . "/content-header.php");

$user_id = GetLoginId($_COOKIE['t']);
?>

<div class="container">
  <?php NewerElderNav($newer_row, $elder_row); ?>
    <div class="main">
  <?php
  if ($article_meta) {
    echo '<div class="article-title-bar">';
      echo '<div class="article-title-body">';
        printf('<h2 class="article-title-text">%s</h2>', stripslashes($article_meta['a_title']));
      echo '</div>';
      echo '<div id="right-bar">';
      if ($user_id > 0) {
        try {
        $redis = new Redis();
        $redis->connect($REDIS_IP, $REDIS_PORT, 3);
        if ($redis->sismember(GetFavoriteKey($user_id), $article_id)) {
          echo '<a id="remove-favorite" href="#nogo">取消收藏</a>';
        } else {
          echo '<a id="add-favorite" href="#nogo">收藏本文</a>';
        }
        } catch (Exception $e) {
        }
      } else {
        echo '<a id="add-favorite" href="#nogo">收藏本文</a>';
      }
      echo '</div>';
    print('</div>');

    print('<div class="content article_body"><div class="source-desc">');
    printf('类别 : <a href="/cat%d/">%s</a> ', $article_meta['a_category'], $category_map[$article_meta['a_category']]['name']);
    if ($article_meta['u_id'] > 0) {
      printf(' &nbsp; 作者: <a target="_blank" title="%s:%s" href="/u%d/">%s</a>', $article_meta['u_name'], $article_meta['u_title'],
        $article_meta['u_id'], $article_meta['u_name']);
    }
    printf('&nbsp; <span style="font-size:12px;">%s </span>', $article_meta['a_create_time']);  
    print('</div>');
    ?>
    <div id="jz_google_ad" style="float:right;width:300px;height:250px;margin:-9px 2px 0px 4px;">
      <script type="text/javascript">
        google_ad_client = "ca-pub-8814199876982868";
        google_ad_slot = "3538925218";
        google_ad_width = 300;
        google_ad_height = 250;
      </script>
      <script type="text/javascript" src="http://pagead2.googlesyndication.com/pagead/show_ads.js"></script>
    </div>
    <?php
      include_once(dirname(__FILE__) . "/article-main-adapter.php");
      $article_main_adapter = new ArticleMainAdapter();
      $content = $article_main_adapter->GetContent($article_id);
      if (!$content) {
        $content = $article_main_adapter->GetContent($article_id);
      }
      print($content);
    ?>
    <div id="sns-share-bar"></div>
    <div id="user-comments" style="width:97%;clear: both;float: left;margin: 6px 0 16px 6px;">
      <?php 
        echo '<div id="comments_list">';
        $comment_service_adapter = new CommentServiceAdapter();
        $comments_count = $comment_service_adapter->GetArticleCommentCount($article_id);
        $count_per_page = 10;

        $comments_result = null;
        if ($comments_count > 0) {
          $comments_result = $comment_service_adapter->GetArticleComments($article_id, 0, $count_per_page);
        }
        if ($comments_result && $comments_result->success) {
          // printf("success = %d<br/>", $comments_result->success);
          // print_r($comments_result);
          foreach($comments_result->comments as $comment) {
            echo '<div class="comment_item">';
            if (true || $comment->sender_id > 0) {
              print('<p class="comment_meta"><span class="sender">' . $comment->sender_name . '</span>' 
                  . '<span class="time">' . date('Y-m-d H:i:s', $comment->time_stamp) . '</span></p>');
            } else {
            }
            print('<p class="comment_content">' . htmlspecialchars($comment->content) . '</p>');
            echo '</div>';
          }
        }
        echo '</div>';

        $total_pages = ceil($comments_count / $count_per_page);
        echo CommonPageNav2($total_pages, $count_per_page, 1, 2, "#comment%d");
      ?>
      <p style="font-weight:bold;font-size:12px;margin:8px 0 0;padding:6px 0 0 2px;">发表评论(最多500字):</p>
      <textarea id="my_comment" style="width:96%;margin:2px auto;height:106px;border: 1px solid #aebacd; overflow: auto;font-size: 14px; line-height: 20px; padding: 4px; resize: none;" autocomplete="off" placeholder="添加评论(无关评论将被管理员删除)"></textarea><br />
      <span style="font-weight:bold;font-size:12px;">昵称：</span>
      <?php
      if ($user_id > 0) {
         $account = GetAccountInfo($user_id);
         echo '<input id="my_name" style="border: 1px solid #aebacd;font-size: 12px;" disabled=true value="' . $account['nick'] . '"/>';
      } else {
         echo '<input id="my_name" style="border: 1px solid #aebacd;font-size: 12px;" value="访客"/>';
      }
      ?>
      <br />
      <span style="font-weight:bold;font-size:12px;"><a id="comment_submit" href="#nogo">提交评论</a><span style="display:none" class="comment_submitting">正在提交...</span></span>
    </div>
  </div>
  <?php
    $related_recomm_adapter = new RelatedRecommAdapter();
    $related_articles = $related_recomm_adapter->GetRelated($article_id);

    if (count($related_articles) > 0) {
      print('<div class="main-related">');
      print('<div class="related-title">相关文章</div>');
      print('<ul class="related-list">');

      $related_count = 0;
      foreach ($related_articles as $i => $value ) {
        $rmeta = GetArticleMeta($value);
        if ($rmeta && $rmeta['a_title']) {
          printf('<li class="related-item"><a target="_blank" href="/a/%d.html">%s</a></li>', $value, stripslashes($rmeta['a_title']));
          if(++$related_count >= 10) {
            break;
          }
        }
      }
      if (count($related_articles) > 0) {
        print('</ul>');
      }
      print('</div>');
    }
  }
  ?>
    </div>
  <?php NewerElderNav($newer_row, $elder_row); ?>

<?php 
  mysql_close($conn);
?>

  <div class="footer">
    <span style="font-weight:bold;">www.<span style="color:#22a;">J</span><span style="color:orange;">Z</span><span style="color:#eb0;">T</span><span style="color:green;">Z</span><span style="color:#a22;">P</span>.com </span> &copy; <span style="font-size:88%;">豫ICP备10022612号</span>
  </div>
</div>
<script type="text/javascript" src="/js/jquery.js"></script>
<script type="text/javascript" src="/js/sl-widgets.5.js"></script>

<script type="text/javascript">
var ref = <?php printf('"%s"', $article_meta['a_url']); ?>;
var g_user_id = <?php printf('%d',$user_id); ?>;

$('img', $('div.content')).each(
  function() {
    if ($(this).attr("src").indexOf('show-img?src=') > 0) {
      $(this).css("visibility", "visible");
      return;
    }
    var src = $(this).attr("real_src");
    if (!src) {
      src = $(this).attr("src");
    }
    if (src.indexOf('http') < 0) {
      // local site
      return;
    }
    if (ref.indexOf('sinaimg.cn/') <= 0) {
      ref = src;
    }
    $(this).attr("src", "/show-img?src=" + encodeURIComponent(src) + "&ref=" + encodeURIComponent(ref));
    // $(this).attr("src", "/show-img?src=" + encodeURIComponent(src));
    $(this).load(
      function() {
        $(this).css("visibility", "visible");
      }
    );
  }         
);

function GoSearch(node) {
  var txt = $('input.search-word', node.parent()).val();
  window.location = 'http://www.jztzp.com/search?q=' + encodeURIComponent(txt) + '&s=1&c=10';
}
$('.search-word').focus(
    function() {
      var o = $(this);
      if (o.hasClass('inactive')) {
        o.val('');
        o.removeClass('inactive');
      }
    })
  .blur(
    function() {
      var o = $(this);
      if (!o.val() || o.val().length <= 0) {
        o.addClass('inactive');
        o.val('输入贵州茅台、巴菲特等');
      }
    });

$('.search-btn').click(
  function() {
    GoSearch($(this));
  }
);

$('.search-word').keyup(
  function(event) {
    if(event.keyCode == 13) {
      GoSearch($(this));
    }
  }
);

function BuildCommentNode(sender_id, sender_name, comment, sent_at) {
  var user_block = '';

  if (1 || sender_id > 0) {
    user_block = '<p  class="comment_meta"><span class="sender">' + escapeHTML(sender_name) + '</span>' 
      + '<span class="time">' + sent_at.pattern('yyyy-MM-dd HH:mm:ss') + '</span></p>';
  } else {
  }
  var html = '<div  class="comment_item">' 
           +  user_block 
           +  '<p  class="comment_content">' + comment + '</p>' 
           + '</div>';
  // alert(html);
  return $(html);
}


function Utf8Bytes(str) {
  // Matches only the 10.. bytes that are non-initial characters in a multi-byte sequence.
  var m = encodeURIComponent(str).match(/%[89ABab]/g);
  return str.length + (m ? m.length : 0);
}

$('#comment_submit').click(
  function(event) {
    var comment = $('#my_comment').val();
    if (!comment) {
      alert("评论不能为空");
      return;
    }

    if (Utf8Bytes(comment) > 1500) {
      alert("评论内容过长");
      return;
    }

    var nick = $('#my_name').val();
    if (!nick) {
      alert("请输入昵称");
      return;
    }
    if (Utf8Bytes(nick) > 30) {
      alert("昵称过长");
      return;
    }

    $(this).hide();
    $('span.comment_submitting').show();
    $.ajax({
      url: "/comment-post.php",
      data: "aid=" + article_id + "&comment=" 
          + encodeURIComponent($('#my_comment').val()) 
          + "&name=" + encodeURIComponent($('#my_name').val()) ,
      type: 'post',
      context : $(this),
      timeout : 3000,
      success : function(rsp_txt) {
        $.globalEval('var o = ' + rsp_txt);
        if (o.code == 0) {
          $('#comments_list').append(BuildCommentNode(g_user_id, $('#my_name').val(), $('#my_comment').val(), new Date()));
          $('#my_comment').val("");
        } else {
          alert(o.reason);
        }
        $(this).show();
        $('span.comment_submitting').hide();
      }, 
      error : function(xhr, text_status, err){
        alert('提交失败:' + text_status);
        $(this).show();
        $('span.comment_submitting').hide();
      }
    });
  }
);


$('#add-favorite').click(
  function(event) {
    $.ajax({
      url: "/account/add-fav.php?id=" + article_id,
      context : $(this),
      success : function(rsp_txt) {
        $.globalEval('var o = ' + rsp_txt);
        // $(this).parent().html(o.reason + o.code);
        if (o.code == 1) {
          $(this).parent().html('请先<a href="/account/login.php?d=' + encodeURIComponent('/a/' + article_id + '.html') + '">登录</a>');
        } else {
          $(this).parent().html(o.reason);
        }
      }
    });
  }
);

$('#remove-favorite').click(
  function(event) {
    $.ajax({
      url: "/account/rm-fav.php?id=" + article_id,
      context : $(this),
      success : function(rsp_txt) {
        $.globalEval('var o = ' + rsp_txt);
        if (o.code == 1) {
          $(this).parent().html('请先<a href="/account/login.php?d=' + encodeURIComponent('/a/' + article_id + '.html') + '">登录</a>');
        } else {
          $(this).parent().html(o.reason);
        }
      }
    });
  }
);

function AddPageNavHandler(root_node) {
  $('a.page-nav', root_node).click(
    function(event) {
      <?php
      echo "var count_per_page = " . $count_per_page . ";";
      echo "var total_pages = " . $total_pages . ";";
      ?>

      var href = $(this).attr("href");
      var page_id = parseInt(href.substr(href.indexOf('#') + "#comment".length)) - 1;

      $.ajax({
        url: "/comment-load.php?aid=" + article_id + "&s=" + (page_id * count_per_page) 
          + "&n=" + count_per_page + '&t=' + total_pages + '&r=' + Math.random(),
        context : $(this),
        success : function(rsp_txt) {
          $.globalEval('var o = ' + rsp_txt);
          if (o.code == 0) {
            $('#comments_list').empty();
            for(var i = 0; i < o.comments.length; ++i) {
              var cur = o.comments[i];
              $('#comments_list').append(BuildCommentNode(cur.sender_id, cur.sender_name, cur.content, new Date(cur.time_stamp * 1000)));
            }

            var nav_dom = $(o.nav_html);
            $('div.page-nav', $('#user-comments')).replaceWith(nav_dom);
            AddPageNavHandler(nav_dom);
          } else {
            alert("加载失败");
          }
        }
      });
    }
  );
}
$(document).ready(
  function() {
    AddPageNavHandler($(this));
  }
);
<?php
// include(dirname(__FILE__) . "/analytics.js");
?>
</script>
</body>
</html>
